package experiment2.task1;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;

/**
 * @author 冯永龙
 * @date 2021/3/23 15:38
 */
class test {
    public static void main(String[] args) throws IOException {
        Person person = new Person();
        person.setIdNo("5122245566");
        person.setName("张小平");
        person.setAge(23);
        person.setSex("Male");
        person.setMerried(true);

    }

    public static void printFile( Person person){
        Class clazz = person.getClass();
        Field[] fields = clazz.getDeclaredFields();
        Writer writer = null;
        BufferedWriter bufferedWriter = null;
        String file = "src/experiment2/task1/person";

        try {

            //覆盖写
            writer = new FileWriter(file);
            bufferedWriter = new BufferedWriter(writer);

            for (Field field : fields) {
                field.setAccessible(true); //暴力反射
                bufferedWriter.write(field.getName() + "=" + field.get(person) + "\n");
                field.setAccessible(false); //将属性访问权还原
            }

            bufferedWriter.flush(); //清除缓冲区，确保数据写入

        } catch (IOException e) {
            System.out.println("写入文件失败");
            e.printStackTrace();

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } finally {
            try {
//                System.out.println("写入文件成功");
                writer.close();
                bufferedWriter.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
